package io.r2mo.test.jce;

import io.r2mo.base.io.HStore;
import io.r2mo.base.io.HUri;
import io.r2mo.jce.common.HED;
import io.r2mo.jce.component.lic.LicenseService;
import io.r2mo.jce.component.lic.domain.LicenseConfiguration;
import io.r2mo.jce.component.lic.domain.LicenseData;
import io.r2mo.jce.component.lic.domain.LicensePath;
import io.r2mo.jce.component.lic.io.LicenseIo;
import io.r2mo.jce.constant.AlgLicense;
import io.r2mo.jce.constant.LicFormat;
import io.r2mo.spi.SPI;
import io.r2mo.spring.junit5.AppIoTestSupport;
import lombok.extern.slf4j.Slf4j;
import org.junit.jupiter.api.BeforeAll;

/**
 * @author lang : 2025-09-21
 */
@Slf4j
public abstract class AbstractLicenseTestCase extends AppIoTestSupport {
    protected static final AlgLicense LICENSE = AlgLicense.RSA;
    protected static final AlgLicense ENC = AlgLicense.AES;
    protected static final LicFormat FORMAT = LicFormat.TEXT;
    protected static HStore store;
    protected static LicenseIo io;
    protected static LicenseService service;

    @BeforeAll
    public static void init() {
        HED.initialize();
        store = SPI.V_STORE;
        io = LicenseIo.of(store);
        service = LicenseService.of(LICENSE);
        log.info("[ R2MOMO ] 存储对接：{}", store.getClass().getName());
        log.info("[ R2MOMO ] --> 许可证对接：{}", io.getClass().getName());
        log.info("[ R2MOMO ]     许可证服务：{}", service.getClass().getName());
    }

    protected LicenseConfiguration createConfiguration(final boolean encrypted) {
        final LicenseConfiguration configuration = new LicenseConfiguration()
            .ioContext("HED/licensing")
            .algSign(LICENSE);
        if (encrypted) {
            configuration.algEnc(ENC);
        }
        return configuration;
    }

    protected LicensePath createPath(final LicenseData licenseData, final LicFormat format) {
        final String resolved = HUri.UT.resolve(licenseData.licenseId(), licenseData.getId().toString());
        return LicensePath.builder()
            .fileKey(resolved + ".key")
            .fileSign(resolved + ".sig")
            // .fileLicense(resolved + formatFail.extension())
            .id(licenseData.getId())
            .licenseId(licenseData.licenseId())
            .format(format)
            .build();
    }

    protected String readLic(final LicenseData licenseData, final LicFormat format,
                             final LicenseConfiguration configuration) {
        final String path = configuration.contextLicense() +
            "/" + licenseData.licenseId() +
            "/" + licenseData.getId() + format.extension();
        return store.inString(path);
    }
}
